package cn.xfdzx.android.apps.shop.activity;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.activity.ruzhu.AgreementActivity;
import cn.xfdzx.android.apps.shop.adapter.SelectTimeDayLVAdapter;
import cn.xfdzx.android.apps.shop.adapter.SelectTimeLVAdapter;
import cn.xfdzx.android.apps.shop.adapter.XFDConfirmOrderAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.AddressListBeen;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.XFDConfirmOrderBeen;
import cn.xfdzx.android.apps.shop.contract.XFDConfirmOrderContract;
import cn.xfdzx.android.apps.shop.presenter.XFDConfirmOrderPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;

import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;
import static cn.xfdzx.android.apps.shop.apps.Constants.START_CODE;

/**
 * 新发地 商铺 确认订单
 */
public class XFDConfirmOrderActivity extends BaseMvpActivity<XFDConfirmOrderPresenter> implements XFDConfirmOrderContract.View {


    @BindView(R.id.ll_select_address)
    LinearLayout llSelectAddress;
    @BindView(R.id.rl_user_address)
    RelativeLayout rlUserAddress;
    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.rv_order)
    RecyclerView rvOrder;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_total_freight)
    TextView tvTotalFreight;
    @BindView(R.id.tv_pay_total_money)
    TextView tvPayTotalMoney;
    @BindView(R.id.tv_address_tag)
    TextView tvAddressTag;
    @BindView(R.id.tv_address_info)
    TextView tvAddressInfo;
    @BindView(R.id.tv_user_info)
    TextView tvUserInfo;
    @BindView(R.id.tv_immediately_time)
    TextView tvImmediatelyTime;//送达时间
    @BindView(R.id.img_timedes)
    ImageView img_timedes;//送达时间说明
    @BindView(R.id.tv_freightdes)
    TextView tv_freightdes;//运费说明
    @BindView(R.id.tv_goruzhu)
    TextView tv_goruzhu;//去入驻
    @BindView(R.id.ll_goruzhu)
    LinearLayout ll_goruzhu;//去入驻布局
    @BindView(R.id.tv_total_freight_old)
    TextView tv_total_freight_old;//优惠前运费
    @BindView(R.id.tv_freetimes)
    TextView tv_freetimes;//免运费次数

    @BindView(R.id.iv_number_privacy_bg)
    ImageView ivNumberPrivacyBg;
    @BindView(R.id.iv_number_privacy_left)
    ImageView ivNumberPrivacyLeft;
    @BindView(R.id.iv_number_privacy_right)
    ImageView ivNumberPrivacyRight;

    private ShopCarPopupWindow select_time_PW;
    private RelativeLayout.LayoutParams item_bar;
    private ConfirmGoodBeen.DataBean dataBean;

    private XFDConfirmOrderAdapter confirmOrderAdapter;

    private List<ConfirmGoodBeen.DataBean.CartInfoBean> mList = new ArrayList<>();
    private Context mContext;
    private AddressListBeen.DataBean dataAddressInfo;//选择的地址信息
    private String address_id = "";
    private String order_express_type = "1"; //'1-今日2-明日3-后日'
    private String rightName; //选择的时段

    private int oneTimePosition = 0;
    private int twoTimePosition = 0;
    //今天，明天，后天
    private List<String> dayList = new ArrayList<>();
    private boolean isCanSubmitOrder;//是否可以支付
    private String submitOrderErrorMessage="";//错误信息
    private boolean isSelfRaising;//是否可以自提
    private String isSelfRaisingMessage;//错误信息


    @Override
    public int getLayoutId() {
        mContext = this;
        return R.layout.activity_xfdconfirm_order;
    }

    @Override
    public void initView() {
        initHigh();
        mPresenter = new XFDConfirmOrderPresenter();
        mPresenter.attachView(this);

        dataBean = (ConfirmGoodBeen.DataBean) getIntent().getSerializableExtra("data");
        isCanSubmitOrder = dataBean.isIs_can_submit_order();
        submitOrderErrorMessage = dataBean.getSubmit_order_error_message();
        isSelfRaising = dataBean.isIs_self_raising();

        if (null == dataBean.getIs_self_raising_message()) {
            isSelfRaisingMessage = "服务器出错";
        } else {
            isSelfRaisingMessage = dataBean.getIs_self_raising_message();
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvOrder.setLayoutManager(linearLayoutManager);
        rvOrder.setItemAnimator(new DefaultItemAnimator());
//        rvOrder.setFocusableInTouchMode(false);
        rvOrder.setNestedScrollingEnabled(false);
        confirmOrderAdapter = new XFDConfirmOrderAdapter(this, mList);
        rvOrder.setAdapter(confirmOrderAdapter);


        if (null == dataBean.getAddressInfo()) {
            llSelectAddress.setVisibility(View.VISIBLE);
            rlUserAddress.setVisibility(View.GONE);
        } else {
            llSelectAddress.setVisibility(View.GONE);
            rlUserAddress.setVisibility(View.VISIBLE);
            if (dataBean.getAddressInfo().getLabel() == 1) {
                tvAddressTag.setText("家");
            } else if (dataBean.getAddressInfo().getLabel() == 2) {
                tvAddressTag.setText("公司");
            } else if (dataBean.getAddressInfo().getLabel() == 3) {
                tvAddressTag.setText("学校");
            } else {
                tvAddressTag.setVisibility(View.GONE);
            }
            tvAddressInfo.setText(dataBean.getAddressInfo().getAddress_info() + dataBean.getAddressInfo().getHouse_number());
            tvUserInfo.setText(dataBean.getAddressInfo().getRealname() + "        " + dataBean.getAddressInfo().getMobile());
            address_id = dataBean.getAddressInfo().getId() + "";
        }
        mList.clear();
        mList.addAll(dataBean.getCartInfo());
        confirmOrderAdapter.notifyDataSetChanged();
        tvTotalMoney.setText("¥" + dataBean.getPriceGroup().getTotalPrice());
        tvTotalFreight.setText("¥" + dataBean.getPriceGroup().getStorePostage());
        tvPayTotalMoney.setText("¥" + dataBean.getPriceGroup().getPaymentPrice());
//送达时间选择
        if (null != dataBean.getDeliveryTimeList()) {
            if (null != dataBean.getDeliveryTimeList().getSameDay()) {
                if (dataBean.getDeliveryTimeList().getSameDay().size() != 0) {
                    order_express_type = "1";
                    dayList.add("今天");
                    rightName = dataBean.getDeliveryTimeList().getSameDay().get(0).getDeliveryTime();
                    tvImmediatelyTime.setText("今天" + rightName);
                } else {
                    order_express_type = "2";
                }
            } else {
                order_express_type = "2";
            }
            if (null != dataBean.getDeliveryTimeList().getNextDay()) {
                if (dataBean.getDeliveryTimeList().getNextDay().size() != 0) {
                    dayList.add("明天");
                    if (order_express_type.equals("2")) {
                        rightName = dataBean.getDeliveryTimeList().getNextDay().get(0).getDeliveryTime();
                        tvImmediatelyTime.setText("明天" + rightName);
                    }
                } else {
                    order_express_type = "3";
                }
            } else {
                order_express_type = "3";
            }
            if (null != dataBean.getDeliveryTimeList().getThirdDay()) {
                if (dataBean.getDeliveryTimeList().getThirdDay().size() != 0) {
                    dayList.add("后天");
                    if (order_express_type.equals("3")) {
                        rightName = dataBean.getDeliveryTimeList().getThirdDay().get(0).getDeliveryTime();
                        tvImmediatelyTime.setText("后天" + rightName);
                    }
                }
            }
        }

        if (EmptyUtil.isNotEmpty(dataBean.getActive())) {
            if (EmptyUtil.isNotEmpty(dataBean.getActive().getFree_mail_active())) {
                // 活动开始
                if (dataBean.getActive().getFree_mail_active().isIs_free_mail_activity()) {
                    //是零售商家
                    if (dataBean.getActive().getFree_mail_active().getContent().isIs_retail_store()) {
                        ll_goruzhu.setVisibility(View.GONE);
                        tv_freetimes.setVisibility(View.VISIBLE);
                        tv_freetimes.setText("(还剩" + dataBean.getActive().getFree_mail_active().getContent().getRemnant_number() + "次免邮机会)");
                    } else {
                        ll_goruzhu.setVisibility(View.VISIBLE);
                        tv_freetimes.setVisibility(View.GONE);
                    }

                } else {
                    ll_goruzhu.setVisibility(View.GONE);
                }
            }
        }

        if (EmptyUtil.isNotEmpty(dataBean.getPriceGroup().getGoods_weight())) {
            tv_freightdes.setText("运费总计 (总重: " + dataBean.getPriceGroup().getGoods_weight() + "kg)");
        }
        ivNumberPrivacyBg.setTag(false);
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @Override
    public void showLoading() {
        ProgressDialog.getInstance().show(this);
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onXfdConfirmOrderSuccess(XFDConfirmOrderBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE){
            if (bean.getData().getIs_in()==1){
                isCanSubmitOrder=true;
            }else {
                submitOrderErrorMessage=bean.getMsg();
            }
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        if (UtilsData.getPreference(this, "login").getInteger("is_store") == 0) {
            ll_goruzhu.setVisibility(View.VISIBLE);
        } else {
            ll_goruzhu.setVisibility(View.GONE);
        }

    }

    Intent intent;

    @OnClick({R.id.tv_submit_order, R.id.iv_back, R.id.rl_user_address, R.id.ll_select_address, R.id.ll_delivery_time,
            R.id.img_timedes, R.id.tv_freightdes, R.id.tv_goruzhu, R.id.iv_number_privacy_bg})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_number_privacy_bg:
                if (isSelfRaising) {
                    if ((boolean) ivNumberPrivacyBg.getTag()) {
                        ivNumberPrivacyBg.setTag(false);
                        tvTotalFreight.setText("¥" + dataBean.getPriceGroup().getStorePostage());
                        tvPayTotalMoney.setText("¥" + dataBean.getPriceGroup().getPaymentPrice());
                        ivNumberPrivacyBg.setImageResource(R.drawable.number_privacy_bg_hui);
                        ivNumberPrivacyLeft.setVisibility(View.VISIBLE);
                        ivNumberPrivacyRight.setVisibility(View.GONE);
                    } else {
                        tvTotalFreight.setText("¥ 0");
                        tvPayTotalMoney.setText("¥" + dataBean.getPriceGroup().getTotalPrice());
                        ivNumberPrivacyBg.setTag(true);
                        ivNumberPrivacyBg.setImageResource(R.drawable.number_privacy_bg_green);
                        ivNumberPrivacyLeft.setVisibility(View.GONE);
                        ivNumberPrivacyRight.setVisibility(View.VISIBLE);
                    }
                } else {
                    Utils.toastMessage(this, isSelfRaisingMessage);
                }
                break;
            case R.id.tv_submit_order:
                if (!isCanSubmitOrder && !(boolean) ivNumberPrivacyBg.getTag()) {
                    Toast.makeText(this, submitOrderErrorMessage, Toast.LENGTH_SHORT).show();
                }
                if (address_id.isEmpty()) {
                    Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
                    return;
                }
//                if (!isSelfRaising){
//                    Utils.toastMessage(this, isSelfRaisingMessage);
//                    return;
//                }
                    //提交订单
                intent = new Intent(this, PaymentDeskOrderActivity.class);
                intent.putExtra("from", "submit");
                intent.putExtra("orderKey", dataBean.getOrderKey());
                intent.putExtra("address_id", address_id);
                intent.putExtra("order_express_type", order_express_type);
                intent.putExtra("rightName", rightName);
                String marks = "";
                for (ConfirmGoodBeen.DataBean.CartInfoBean cartInfoBean : mList) {
                    if (marks.isEmpty()) {
                        marks = "\"" + cartInfoBean.getStore().getId() + "\"" + ":" + "\"" + cartInfoBean.getPriceGroup().getNote() + "\"";
                    } else {
                        marks = marks + ",\"" + cartInfoBean.getStore().getId() + "\"" + ":" + "\"" + cartInfoBean.getPriceGroup().getNote() + "\"";
                    }
                }
                marks = "{" + marks + "}";
                Log.e("备注", marks);
                intent.putExtra("marks", marks);
                intent.putExtra("logistics_type", dataBean.getIs_delivery() + "");
                if ((boolean) ivNumberPrivacyBg.getTag()) {
                    intent.putExtra("totalMoney", dataBean.getPriceGroup().getTotalPrice() + "");
                    intent.putExtra("delivery_method", "2");
                } else {
                    intent.putExtra("totalMoney", dataBean.getPriceGroup().getPaymentPrice() + "");
                    intent.putExtra("delivery_method", "");
                }
                startActivity(intent);

                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_user_address:
                //跳转到地址管理
                intent = new Intent(mContext, ManagementAddressActivity.class);
                intent.putExtra("from", "confirm");

                startActivityForResult(intent, START_CODE);
                break;
            case R.id.ll_select_address:
                //跳转到新增收货地址
                intent = new Intent(mContext, AddAddressActivity.class);
                intent.putExtra("from", "confirm");
                intent.putExtra("is_default", "1");
                intent.putExtra("id", "");
                startActivityForResult(intent, START_CODE);
                break;
            case R.id.ll_delivery_time:
                showTime();
                break;
            case R.id.img_timedes://送达时间说明
                intent = new Intent(mContext, OrderFeightDesActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("state", "1");
                startActivity(intent);
                break;
            case R.id.tv_freightdes://运费总计说明
                intent = new Intent(mContext, OrderFeightDesActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("state", "2");
                startActivity(intent);
                break;
            case R.id.tv_goruzhu://去入驻
                if (EmptyUtil.isNotEmpty(APP_TOKEN)) {
                    if (UtilsData.getPreference(this, "login").getInteger("is_store") == 0) {
                        intent = new Intent(this, AgreementActivity.class);
                        intent.putExtra("type", "0");
                        startActivity(intent);
                    }

                } else {

                    Intent intent = new Intent(this, OneLoginMainActivity.class);
                    startActivity(intent);
                }
                break;
        }

    }


    @Override
    protected void onDestroy() {
        if (select_time_PW != null) {
            if (select_time_PW.isShowing()) {
                select_time_PW.dismiss();
            }
            select_time_PW = null;
        }
        dayList.clear();
        dayList = null;
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (select_time_PW != null) {
            if (select_time_PW.isShowing()) {
                select_time_PW.shareClose();
                return;
            }
        }
        super.onBackPressed();
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == START_CODE) {
                if (rlUserAddress.getVisibility() == View.GONE) {
                    llSelectAddress.setVisibility(View.GONE);
                    rlUserAddress.setVisibility(View.VISIBLE);
                }
                dataAddressInfo = (AddressListBeen.DataBean) data.getSerializableExtra("data");
                address_id = dataAddressInfo.getId() + "";
                tvAddressTag.setVisibility(View.VISIBLE);
                if (dataAddressInfo.getLabel() == 1) {
                    tvAddressTag.setText("家");
                } else if (dataAddressInfo.getLabel() == 2) {
                    tvAddressTag.setText("公司");
                } else if (dataAddressInfo.getLabel() == 3) {
                    tvAddressTag.setText("学校");
                } else {
                    tvAddressTag.setVisibility(View.GONE);
                }
                tvAddressInfo.setText(dataAddressInfo.getAddress_info() + dataAddressInfo.getHouse_number());
                tvUserInfo.setText(dataAddressInfo.getRealname() + "        " + dataAddressInfo.getMobile());
                isCanSubmitOrder=false;
                mPresenter.xfdConfirmOrder(dataBean.getOrderKey(), address_id);
            }
        }
    }


    private void showTime() {
        if (select_time_PW != null) {

        } else {
            select_time_PW = new ShopCarPopupWindow(this, R.layout.pw_select_time);
            select_time_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    select_time_PW.shareClose();
                }
            });
            //时间右侧数据
            SelectTimeLVAdapter selectTimeLVAdapter = new SelectTimeLVAdapter(mContext, dataBean.getDeliveryTimeList().getSameDay());
            //时间左侧天数
            SelectTimeDayLVAdapter selectTimeDayLVAdapter = new SelectTimeDayLVAdapter(this, dayList);
            ((ListView) select_time_PW.getRootView().findViewById(R.id.lv_day)).setAdapter(selectTimeDayLVAdapter);
            ((ListView) select_time_PW.getRootView().findViewById(R.id.lv_day)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    selectTimeDayLVAdapter.setOnItme(position);
                    oneTimePosition = position;
                    if (dayList.get(position).equals("今天")) {
                        selectTimeLVAdapter.setData(dataBean.getDeliveryTimeList().getSameDay());
                        if (order_express_type.equals("1")) {
                            selectTimeLVAdapter.setItem(true, twoTimePosition);
                        } else {
                            selectTimeLVAdapter.setItem(false, twoTimePosition);
                        }
                    } else if (dayList.get(position).equals("明天")) {
                        selectTimeLVAdapter.setData(dataBean.getDeliveryTimeList().getNextDay());
                        if (order_express_type.equals("2")) {
                            selectTimeLVAdapter.setItem(true, twoTimePosition);
                        } else {
                            selectTimeLVAdapter.setItem(false, twoTimePosition);
                        }
                    } else if (dayList.get(position).equals("后天")) {
                        selectTimeLVAdapter.setData(dataBean.getDeliveryTimeList().getThirdDay());
                        if (order_express_type.equals("3")) {
                            selectTimeLVAdapter.setItem(true, twoTimePosition);
                        } else {
                            selectTimeLVAdapter.setItem(false, twoTimePosition);
                        }
                    }
                }
            });
            if (order_express_type.equals("1")) {
                selectTimeLVAdapter.setData(dataBean.getDeliveryTimeList().getSameDay());
            } else if (order_express_type.equals("2")) {
                selectTimeLVAdapter.setData(dataBean.getDeliveryTimeList().getNextDay());
            } else if (order_express_type.equals("3")) {
                selectTimeLVAdapter.setData(dataBean.getDeliveryTimeList().getThirdDay());
            }
            ((ListView) select_time_PW.getRootView().findViewById(R.id.lv_time)).setAdapter(selectTimeLVAdapter);
            ((ListView) select_time_PW.getRootView().findViewById(R.id.lv_time)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    twoTimePosition = position;
                    if (dayList.get(oneTimePosition).equals("今天")) {
                        order_express_type = "1";
                        rightName = dataBean.getDeliveryTimeList().getSameDay().get(twoTimePosition).getDeliveryTime();
                        tvImmediatelyTime.setText("今天" + rightName);
                    } else if (dayList.get(oneTimePosition).equals("明天")) {
                        order_express_type = "2";
                        rightName = dataBean.getDeliveryTimeList().getNextDay().get(twoTimePosition).getDeliveryTime();
                        tvImmediatelyTime.setText("明天" + rightName);
                    } else if (dayList.get(oneTimePosition).equals("后天")) {
                        order_express_type = "3";
                        rightName = dataBean.getDeliveryTimeList().getThirdDay().get(twoTimePosition).getDeliveryTime();
                        tvImmediatelyTime.setText("后天" + rightName);
                    }
                    selectTimeLVAdapter.setItem(true, twoTimePosition);
                    select_time_PW.shareClose();
                }
            });
        }
        select_time_PW.showPopupWindow();
    }
}
